

# 初始化配置
import redis
from flask import Flask
from flask import g
from flask import render_template
from flask.ext.session import Session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from flask.ext.wtf.csrf import generate_csrf

from config import Config, set_log
from info.utils.common import user_logo_data

db=SQLAlchemy()
redis_store=None  # type:redis.StrictRedis

def creat_app(config_name):
    app=Flask(__name__)
    # set_log(config_name)
    # 初始化配置
    app.config.from_object(Config)
    # 实例化mysql数据库
    db.init_app(app)
    global redis_store
    redis_store=redis.StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT,decode_responses=True)
    CSRFProtect(app)
    Session(app)
    #每次请求之后对响应做更改（请求钩子）
    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token',csrf_token)
        return response

    @app.errorhandler(404)
    @user_logo_data
    def error_page(e):
        user=g.user
        data={
            'user':user
        }
        return render_template('news/404.html',data=data)


    from info.modules.index import blue_url

    app.register_blueprint(blue_url)

    from info.modules.passport import passport_url
    app.register_blueprint(passport_url)
    print()
    #添加过滤器index_Class 过滤新闻排行榜第一第二第三的排行显示的css
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class,'index_Class')
    # 注册新闻详情页面的蓝图
    from info.modules.news import news_url
    app.register_blueprint(news_url)

    # 注册个人中心详情页蓝图
    from info.modules.profile import profile_url
    app.register_blueprint(profile_url)

    # 注册管理员中心蓝图
    from info.modules.admin import admin_url
    app.register_blueprint(admin_url,url_prefix="/admin")

    return app

